const http = require('https');
const cheerio = require('cheerio');
const fs = require('fs');
const db = require('../db/index')

var CapterData = [{
  titleName: "",
  titleLink: "",
  content: ""
}];
var html = '';
var Forindex = 0;
//数据库操作
const RunSql = async (sql, val) => {
  return new Promise(resolve => {
    db.query(sql, val, (err, result) => {
      if (err) {
        console.log(err);
        return err;
      }
      resolve(result)
    })
  })
}
//接口获取数据并且返回到某个函数中
function HttpData(url, callback) {
  let res = new Promise((reslove, reject) => {
    console.log(url, 'aa');
    http.get(url, function (req, res) {

      req.on('data', function (data) {
        html += data;
      })
      req.on('end', function () {
        console.log(html);
        const $ = cheerio.load(html, {
          decodeEntities: false
        })
        reslove(callback($))
      })
    })
  }).catch(err => {
    console.log(err);
  })
  return res;
}
//获取章节目录
function getCapterData($) {
  var reg = /(?<=[href="]).*?(?=["])/g;
  $('.book-dir').next().children().each((index, ele) => {
    let Link = $(ele).html().match(reg);
    let Name = $(ele).text();
    CapterData.push({
      no: index,
      titleName: Name,
      titleLink: Link[5],
      content: ""
    });
  });
  return CapterData;
}
//获取内容
function getContent($) {
  console.log(Forindex);
  let content = $('#__nuxt #article').eq(Forindex).html();
  Forindex++;
  return content;
}

exports.getNovalData = async function () {
  let capterRes = await HttpData("https://book.qq.com/book-detail/46017017", getCapterData);
  console.log(capterRes);
  /* const insertSql = 'insert into  NovalCapater set ?'
  let res = await RunSql(insertSql, capterRes); */
  capterRes.map(async (it, index) => {
    console.log(index);
    if (index == 33) {
      console.log(it.titleLink);
      if (it.titleLink) {
        // setTimeout(async () => {
        let connectLink = "https:" + it.titleLink;
        let NovelContent = await HttpData(connectLink, getContent);
        console.log(NovelContent);
        /* const insertSql = 'insert into  NovalCapater set ?'
        let res = await RunSql(insertSql, it); */
        const insertSql = 'update NovalCapater set content=? where titleLink=?'
        let res = await RunSql(insertSql, [JSON.stringify(NovelContent), it.titleLink]);
        console.log(res);
        // }, 1000)
      }
    }
  })
}